package org.bsscheduler;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author tblackstone
 */
public class SendMail {

    private static final String configFile = "mailconf.txt";
    private static Properties mailServerSettings = new Properties();

    public static void send(String mailTo, String subject, String body) {
        Session session = Session.getDefaultInstance(mailServerSettings, null);
        MimeMessage message = new MimeMessage(session);
        try {
            message.addRecipient(
                    Message.RecipientType.TO, new InternetAddress(mailTo));

            message.setSubject(subject);
            message.setText(body);
            Transport.send(message);
        } catch (MessagingException ex) {
            System.err.println("Cannot send email. " + ex);
        }

    }


    static {
        loadConfig();
    }

    private static void loadConfig() {
            InputStream input = null;
            try {
                File f = new File(configFile);
                System.out.println("Looking for mail server properties file in: "
                        + f.getAbsolutePath());
                input = new FileInputStream(configFile);
                mailServerSettings.load(input);
            } catch (IOException ex) {
                System.err.println("Cannot load mail server properties file.");
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                } catch (IOException ex) {
                    System.err.println("Cannot close mail server properties file.");
                }
            }
        }
    }
